package conf

import (
	"flag"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"go-base/hs-gin/utils"
)

var Configer *config

type config struct {
	ApiConf   ApiConfig
	DbConf    DbConfig
	CacheConf RedisConfig
	//BeeConfiger beeConfig.Configer
}

func NewConfiger(filename string) {
	Configer = new(config)

	var err error
	var fileName string
	// 格式化命令行参数
	flag.StringVar(&fileName, "c", filename, "conf file")
	flag.Parse()
	// 载入配置文件
	if err := utils.SetViperConfigFile(fileName); err != nil {
		panic(err.Error())
	}

	if err != nil {
		panic("读取配置文件出错")
	}

	Configer.load()
}

//加载配置到内存
func (c *config) load() {
	var err error

	//系统配置
	c.ApiConf.HttpPort = viper.GetString("system.httpPort")
	c.ApiConf.RpcPort = viper.GetString("system.rpcPort")
	c.ApiConf.RunMode = viper.GetString("system.runMode")
	c.ApiConf.ParamSecret = viper.GetString("system.paramSecret")

	if viper.GetString("system.workerId") != "" {
		c.ApiConf.WorkerID = viper.GetInt64("system.workerId")
		if err != nil {
			panic("读取system.workerId配置出错")
		}
	}

	//日志配置
	c.ApiConf.LogPath = viper.GetString("log.path")
	c.ApiConf.LogLevel = viper.GetString("log.level")

	//数据库配置
	c.DbConf.DriverName = viper.GetString("db.driverName")
	c.DbConf.Host = viper.GetString("db.host")
	c.DbConf.Port = viper.GetString("db.port")
	c.DbConf.User = viper.GetString("db.user")
	c.DbConf.Password = viper.GetString("db.password")
	c.DbConf.Database = viper.GetString("db.database")
	c.DbConf.TimeZone = viper.GetString("db.timeZone")
	c.DbConf.Charset = viper.GetString("db.charset")
	c.DbConf.MaxIdleConns = viper.GetInt("db.maxIdleConn")
	c.DbConf.MaxOpenConns = viper.GetInt("db.maxOpenConn")
	c.DbConf.ShowLog = viper.GetBool("db.showLog")

	//redis配置
	if viper.GetString("cache.host") != "" {
		c.CacheConf.DriverName = viper.GetString("cache.driverName")
		c.CacheConf.Host = viper.GetString("cache.host")
		c.CacheConf.Port = viper.GetString("cache.port")
		c.CacheConf.Password = viper.GetString("cache.password")
		c.CacheConf.DB = viper.GetInt("cache.db")
		c.CacheConf.MaxIdleConns = viper.GetInt("cache.maxIdle")
		c.CacheConf.MaxActive = viper.GetInt("cache.maxActive")
		c.CacheConf.IdleTimeout = viper.GetInt("cache.idleTimeoutSec")
		//if err != nil {
		//	panic("读取redis.db配置出错")
		//}
	}

	//判断配置
	if c.ApiConf.RunMode != gin.DebugMode && c.ApiConf.RunMode != gin.TestMode && c.ApiConf.RunMode != gin.ReleaseMode {
		panic("run_mode配置错误")
	}
	if c.ApiConf.LogLevel != "debug" && c.ApiConf.LogLevel != "info" && c.ApiConf.LogLevel != "error" {
		panic("log_level配置错误")
	}
}
